// firmware.js

let isBleConnected = false;
const FW_BLOCK_SIZE = 20;
const TOTAL_BLOCKS = 100;

let upgradeState = "idle"; // 可选：idle, start, transferring, verify, complete

// 模拟固件数据
const firmwareImage = [];

for (let i = 0; i < TOTAL_BLOCKS; i++) {
    const block = new Uint8Array(FW_BLOCK_SIZE);
    for (let j = 0; j < FW_BLOCK_SIZE; j++) {
        block[j] = Math.floor(Math.random() * 256); // 模拟二进制数据
    }
    firmwareImage.push(block);
}

let currentBlockIndex = 0;

// 模拟 BLE 发送函数
function sendBlePacket(data) {
    console.log(`[BLE] Sending packet: Block ${currentBlockIndex}, Size: ${data.length}`);
    // 在真实场景中调用 navigator.bluetooth 或 WebSocket 等方式
}

// 处理控制命令
function onControlCharWrite(command) {
    if (!isBleConnected) return;

    switch (command) {
        case 0x01:
            upgradeState = "start";
            console.log("Upgrade started");
            sendNextBlock();
            break;
        case 0x02:
            console.log("Resend last block");
            resendLastBlock();
            break;
        case 0x03:
            upgradeState = "verify";
            console.log("Verifying firmware...");
            verifyFirmware();
            break;
    }
}

// 发送下一个数据块
function sendNextBlock() {
    if (currentBlockIndex >= TOTAL_BLOCKS) {
        console.log("All blocks sent.");
        return;
    }

    const block = firmwareImage[currentBlockIndex];
    const packet = new Uint8Array(FW_BLOCK_SIZE + 2);
    packet[0] = currentBlockIndex & 0xFF;
    packet[1] = (currentBlockIndex >> 8) & 0xFF;
    packet.set(block, 2);

    sendBlePacket(packet.buffer);

    console.log(`Sent block ${currentBlockIndex + 1}/${TOTAL_BLOCKS}`);
    currentBlockIndex++;
}

// 重发上一个数据块
function resendLastBlock() {
    if (currentBlockIndex === 0) return;
    console.log(`Resending block ${currentBlockIndex}`);
    currentBlockIndex--; // 回退索引
    sendNextBlock();
}

// 验证固件完整性
function verifyFirmware() {
    const calculatedChecksum = calculateChecksum();
    const expected = expectedChecksum();

    if (calculatedChecksum === expected) {
        console.log("Firmware verified successfully.");
        upgradeState = "complete";
        sendUpgradeComplete();
    } else {
        console.error("Firmware verification failed.");
        sendUpgradeFailed();
    }
}

// 计算校验和
function calculateChecksum() {
    let sum = 0;
    for (let i = 0; i < TOTAL_BLOCKS; i++) {
        for (let j = 0; j < FW_BLOCK_SIZE; j++) {
            sum += firmwareImage[i][j];
        }
    }
    return sum >>> 0; // 32位无符号整数
}

// 获取预期校验和（模拟）
function expectedChecksum() {
    return calculateChecksum(); // 假设一致
}

// 发送升级完成通知
function sendUpgradeComplete() {
    const signal = new Uint8Array([0x01]);
    sendBlePacket(signal.buffer);
    console.log("Upgrade completed successfully");
}

// 发送升级失败通知
function sendUpgradeFailed() {
    const signal = new Uint8Array([0x00]);
    sendBlePacket(signal.buffer);
    console.log("Upgrade failed");
}

// 初始化
function initFirmwareUpgrade() {
    console.log("Firmware upgrade module initialized");
    isBleConnected = true;
}

// 模拟开始升级
initFirmwareUpgrade();

// 示例：触发升级流程
setTimeout(() => {
    onControlCharWrite(0x01); // 启动升级
}, 1000);

// 每隔一定时间发送下一块（模拟异步传输）
setInterval(() => {
    if (upgradeState === "transferring") {
        sendNextBlock();
    }
}, 500);